﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 渐变
{
    public partial class CarManager : Form
    {

        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case 0x84:
                    base.WndProc(ref m);
                    if ((int)m.Result == 0x1)
                        m.Result = (IntPtr)0x2;
                    return;
            }

            base.WndProc(ref m);
        }
        public CarManager()
        {
            InitializeComponent();
        }
       
        /*加载datagridview数据*/
        public void loadMsg()
        {
            Console.WriteLine("已进入");
            /* this.pageSize = 30;
             this.CurrentPage = 1;
             string sql = "select CId,CName,CPrice,CImg,CNumber,CarInfo.CTypeId,CarTypeInfo.CTypeId,CTitle from CarInfo,CarTypeInfo where CarInfo.CTypeId=CarTypeInfo.CTypeId and CarInfo.CIsDelete=0";
             DataTable dt = DBHelper.ExecuteQuery(sql);
             //设置是否允许自动生成列
             carData.AutoGenerateColumns = false;
             BindPage();*/
            this.source = new DataSet();
            this.pageSize = 10;
            this.CurrentPage = 1;
            string connstring = System.Configuration.ConfigurationSettings.AppSettings["connstring"].ToString();
            SqlConnection conn = new SqlConnection(connstring);
            conn.Open();
            string sql = "select CId,CName,CPrice,CImg,CNumber,CarInfo.CTypeId,CStatus,CarTypeInfo.CTypeId,CTitle from CarInfo,CarTypeInfo where CarInfo.CTypeId=CarTypeInfo.CTypeId and CarInfo.CIsDelete=0";
            carData.AutoGenerateColumns = false;
            DataAdapter adapter = new SqlDataAdapter(sql, conn);
            adapter.Fill(source);
            
            BindPage();
        }
        private void CarManager_Load(object sender, EventArgs e)
        {
            this.Dock = DockStyle.Fill;
            loadMsg();

        }

        private void addCar_Click(object sender, EventArgs e)
        {
            addCarForm addCarForm = new addCarForm();
            DialogResult dr = addCarForm.ShowDialog();
            if(dr == DialogResult.OK)
            {
                loadMsg();
            }
        }
        //展示数据
        private void GetData()
        {
            string sql = "select * from CarInfo";
            DataTable dt = DBHelper.ExecuteQuery(sql);
            carData.ClearSelection();//取消选择第一行
            carData.DataSource = dt;
        }
        //dataGridView事件里面的，头像列需要设置为图片格式

        private void carData_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (carData.Columns[e.ColumnIndex].Name.Equals("Image"))
            //if (demoGrid.Columns[e.ColumnIndex].Name.Equals("img"))
            {

                if (e.Value.GetType() == typeof(string))
                {
                    byte[] str = Convert.FromBase64String(e.Value.ToString().Replace("data:image/jpg;base64,", "").ToString());
                    e.Value = GetImage(str);
                }
               
            }
        }
        public Image GetImage(byte[] str)
        {
            MemoryStream ms = new MemoryStream(str);
            Image img = System.Drawing.Image.FromStream(ms);
            return img;
        }

        int pageCount = 0;
        public int PageCount
        {
            get
            {
                if (source != null)
                {
                    pageCount = (int)Math.Ceiling(source.Tables[0].Rows.Count * 1.0 / pageSize);
                }
                return pageCount;
            }
        }

        DataSet source;//用于存储数据库中的查询出来的数据
        int pageSize = 5;//每页条目数
        int currentPage = 1;
        /// <summary>
        /// 当前页
        /// </summary>
        public int CurrentPage
        {
            get { return currentPage; }
            set
            {
                if (value <= 1)
                {
                    value = 1;
                    this.bdFirstItem.Enabled = false;
                    this.bdPreviousItem.Enabled = false;
                    this.bdNextItem.Enabled = true;
                    this.bdLastItem.Enabled = true;
                }
                else if (value >= PageCount)
                {
                    value = pageCount;
                    this.bdFirstItem.Enabled = true;
                    this.bdPreviousItem.Enabled = true;
                    this.bdNextItem.Enabled = false;
                    this.bdLastItem.Enabled = false;
                }
                else
                {
                    this.bdFirstItem.Enabled = true;
                    this.bdPreviousItem.Enabled = true;
                    this.bdNextItem.Enabled = true;
                    this.bdLastItem.Enabled = true;

                }
                currentPage = value;
            }
        }
        int currentRow;
        /// <summary>
        /// 每页首行索引
        /// </summary>
        public int CurrentRow
        {
            get
            {
                if (CurrentPage == 1)
                {
                    currentRow = 0;
                }
                else
                {
                    currentRow = (CurrentPage - 1) * pageSize;
                }
                return currentRow;
            }
        }
        int max = 0;
        /// <summary>
        /// 每页行数最大值索引
        /// </summary>
        public int Max
        {
            get
            {
                if (CurrentPage == pageCount)
                {
                    max = source.Tables[0].Rows.Count;
                }
                else
                {
                    max = pageSize * CurrentPage;
                }
                return max;
            }
        }
        /// <summary>
        /// 绑定combobox中的页码
        /// </summary>
        private void BindPage()
        {
            this.bdCountItem.Text = PageCount.ToString();
            this.tspcbo.Items.Clear();
            for (int i = 1; i <= pageCount; i++)
            {
                this.tspcbo.Items.Add("第" + i + "页");
            }
            this.tspcbo.SelectedIndex = 0;
        }
        /// <summary>
        /// 分页绑定数据
        /// </summary>
        private void BindSourceFY()
        {
            DataTable dt = new DataTable();
            //dt.TableName = "tb";//这个可以没有
            //下面这个循环比较有用，没有这个循环直接绑定的话datagridview是不显示数据的
            //原因是在dt这个对象里面那个columns集合是空，所以这个datagridview没有办法自动绑定 列的名字可以根据自己的需要添加想要的名字
            for (int i = 0; i < source.Tables[0].Columns.Count; i++)
            {
                dt.Columns.Add(source.Tables[0].Columns[i].ToString());
            }
            for (int i = CurrentRow; i < Max; i++)
            {
                dt.ImportRow(source.Tables[0].Rows[i]);
            }
            this.carData.DataSource = dt;
            //this.dgv.DataMember = "tb";

        }

        private void tspcbo_SelectedIndexChanged(object sender, EventArgs e)
        {
            CurrentPage = this.tspcbo.SelectedIndex + 1;
            this.bdPositionItem.Text = CurrentPage.ToString();
            BindSourceFY();

        }

        private void bdFirstItem_Click(object sender, EventArgs e)
        {
            this.tspcbo.SelectedIndex = 0;
        }

        /// <summary>
        /// 前一页
        /// </summary>
        private void bdPreviousItem_Click(object sender, EventArgs e)
        {
            this.tspcbo.SelectedIndex = CurrentPage - 2;
        }

        private void bdNextItem_Click(object sender, EventArgs e)
        {
            this.tspcbo.SelectedIndex = CurrentPage;

        }

        private void bdLastItem_Click(object sender, EventArgs e)
        {
            this.tspcbo.SelectedIndex = PageCount - 1;
        }

        //删除按钮（批量删除）
        private void btnDelete_Click(object sender, EventArgs e)
        {
            DialogResult RSS = MessageBox.Show(this, "确定要删除选中行数据码？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            switch (RSS)
            {
                case DialogResult.Yes:
                    for (int i = this.carData.SelectedRows.Count; i > 0; i--)
                    {
                        int CId = Convert.ToInt32(carData.SelectedRows[i - 1].Cells[0].Value);
                        carData.Rows.RemoveAt(carData.SelectedRows[i - 1].Index);
                        //使用获得的ID删除数据库的数据
                        string sql = "delete  from CarInfo where CId=@CId";
                        int s = DBHelper.ExecuteNonQuery(sql, new SqlParameter("@uid", CId));
                        if (s != 0)
                        {
                            MessageBox.Show("成功删除选中行数据！");
                        }
                    }
                    break;
                case DialogResult.No:
                    break;
            }
        }

        private void carData_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            /*editCarForm editCarForm = new editCarForm();
            int numHang = this.carData.CurrentRow.Index;
            editCarForm.Value = this.carData.Rows[numHang].Cells[0].Value.ToString();
            editCarForm.ShowDialog();*/
            
        }
    }
}
